[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import type {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName, useEditorModeClassName } from '~/client/services/layout';
  19. import { PageView } from '~/components/Page/PageView';
  20. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript'; import type { CrowiRequest } from '~/interfaces/crowi-request';
  21. import type { EditorConfig } from '~/interfaces/editor-settings';
  22. import type { IPageGrantData } from '~/interfaces/page';
  23. import type { RendererConfig } from '~/interfaces/services/renderer';
  24. import type { PageModel, PageDocument } from '~/server/models/page';
  25. import type { PageRedirectModel } from '~/server/models/page-redirect';
  26. import {
  27. useCurrentUser,
  28. useIsForbidden, useIsSharedUser,
  29. useIsEnabledStaleNotification, useIsIdenticalPath,
  30. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  31. useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  32. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  33. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPathname,
  34. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  35. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  36. } from '~/stores/context';
  37. import { useEditingMarkdown } from '~/stores/editor';
  38. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  39. import {
  40. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  41. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  42. } from '~/stores/page';
  43. import { useRedirectFrom } from '~/stores/page-redirect';
  44. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  45. import { useSelectedGrant } from '~/stores/ui';
  46. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  47. import loggerFactory from '~/utils/logger';
  48. import { BasicLayout } from '../components/Layout/BasicLayout';
  49. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  50. import type { GrowiSubNavigationSwitcherProps } from '../components/Navbar/GrowiSubNavigationSwitcher';
  51. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  52. import type { NextPageWithLayout } from './_app.page';
  53. import type { CommonProps } from './utils/commons';
  54. import {
  55. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR,
  56. } from './utils/commons';
  57. declare global {
  58. // eslint-disable-next-line vars-on-top, no-var
  59. var globalEmitter: EventEmitter;
  60. }
  61. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  62. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  63. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  64. const GrowiSubNavigationSwitcher = dynamic<GrowiSubNavigationSwitcherProps>(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  65. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  66. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  67. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  68. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  69. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  70. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  71. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  72. const logger = loggerFactory('growi:pages:all');
  73. const {
  74. isPermalink: _isPermalink, isCreatablePage,
  75. } = pagePathUtils;
  76. const { removeHeadingSlash } = pathUtils;
  77. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  78. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  79. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  80. {
  81. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  82. return v?.data != null
  83. && v?.data.toObject != null
  84. && v?.meta != null
  85. && isIPageInfoForEntity(v.meta);
  86. },
  87. serialize: (v) => {
  88. return {
  89. data: superjson.stringify(v.data.toObject()),
  90. meta: superjson.stringify(v.meta),
  91. };
  92. },
  93. deserialize: (v) => {
  94. return {
  95. data: superjson.parse(v.data),
  96. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  97. };
  98. },
  99. },
  100. 'IPageToShowRevisionWithMetaTransformer',
  101. );
  102. // GrowiContextualSubNavigation for NOT shared page
  103. type GrowiContextualSubNavigationProps = {
  104. isLinkSharingDisabled: boolean,
  105. }
  106. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  107. const { isLinkSharingDisabled } = props;
  108. const { data: currentPage } = useSWRxCurrentPage();
  109. return (
  110. <div data-testid="grw-contextual-sub-nav">
  111. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  112. </div>
  113. );
  114. };
  115. type Props = CommonProps & {
  116. pageWithMeta: IPageToShowRevisionWithMeta | null,
  117. // pageUser?: any,
  118. redirectFrom?: string;
  119. // shareLinkId?: string;
  120. isLatestRevision?: boolean,
  121. isIdenticalPathPage?: boolean,
  122. isForbidden: boolean,
  123. isNotFound: boolean,
  124. isNotCreatable: boolean,
  125. // isAbleToDeleteCompletely: boolean,
  126. templateTagData?: string[],
  127. templateBodyData?: string,
  128. isSearchServiceConfigured: boolean,
  129. isSearchServiceReachable: boolean,
  130. isSearchScopeChildrenAsDefault: boolean,
  131. isSlackConfigured: boolean,
  132. // isMailerSetup: boolean,
  133. isAclEnabled: boolean,
  134. // hasSlackConfig: boolean,
  135. drawioUri: string | null,
  136. hackmdUri: string,
  137. noCdn: string,
  138. // highlightJsStyle: string,
  139. isAllReplyShown: boolean,
  140. isContainerFluid: boolean,
  141. editorConfig: EditorConfig,
  142. isEnabledStaleNotification: boolean,
  143. isEnabledAttachTitleHeader: boolean,
  144. // isEnabledLinebreaks: boolean,
  145. // isEnabledLinebreaksInComments: boolean,
  146. adminPreferredIndentSize: number,
  147. isIndentSizeForced: boolean,
  148. disableLinkSharing: boolean,
  149. skipSSR: boolean,
  150. ssrMaxRevisionBodyLength: number,
  151. grantData?: IPageGrantData,
  152. rendererConfig: RendererConfig,
  153. };
  154. const Page: NextPageWithLayout<Props> = (props: Props) => {
  155. // register global EventEmitter
  156. if (isClient() && window.globalEmitter == null) {
  157. window.globalEmitter = new EventEmitter();
  158. }
  159. const router = useRouter();
  160. useCurrentUser(props.currentUser ?? null);
  161. // commons
  162. useEditorConfig(props.editorConfig);
  163. useCsrfToken(props.csrfToken);
  164. useGrowiCloudUri(props.growiCloudUri);
  165. // page
  166. useIsContainerFluid(props.isContainerFluid);
  167. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  168. useIsForbidden(props.isForbidden);
  169. useIsNotCreatable(props.isNotCreatable);
  170. useRedirectFrom(props.redirectFrom ?? null);
  171. useIsSharedUser(false); // this page cann't be routed for '/share'
  172. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  173. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  174. useIsSearchPage(false);
  175. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  176. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  177. useIsSearchServiceReachable(props.isSearchServiceReachable);
  178. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  179. useIsSlackConfigured(props.isSlackConfigured);
  180. // useIsMailerSetup(props.isMailerSetup);
  181. useIsAclEnabled(props.isAclEnabled);
  182. // useHasSlackConfig(props.hasSlackConfig);
  183. useHackmdUri(props.hackmdUri);
  184. // useNoCdn(props.noCdn);
  185. useDefaultIndentSize(props.adminPreferredIndentSize);
  186. useIsIndentSizeForced(props.isIndentSizeForced);
  187. useDisableLinkSharing(props.disableLinkSharing);
  188. useRendererConfig(props.rendererConfig);
  189. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  190. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  191. useIsAllReplyShown(props.isAllReplyShown);
  192. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  193. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  194. const { pageWithMeta } = props;
  195. const pageId = pageWithMeta?.data._id;
  196. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  197. const revisionBody = pageWithMeta?.data.revision?.body;
  198. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  199. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  200. useCurrentPathname(props.currentPathname);
  201. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  202. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  203. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  204. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  205. const { mutate: mutateIsNotFound } = useIsNotFound();
  206. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  207. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  208. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  209. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  210. const { mutate: mutateRevisionIdHackmdSynced } = useRevisionIdHackmdSynced();
  211. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  212. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  213. useSetupGlobalSocket();
  214. useSetupGlobalSocketForPage(pageId);
  215. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(pageWithMeta?.data);
  216. // Store initial data (When revisionBody is not SSR)
  217. useEffect(() => {
  218. if (!props.skipSSR) {
  219. return;
  220. }
  221. if (currentPageId != null && !props.isNotFound) {
  222. const mutatePageData = async() => {
  223. const pageData = await mutateCurrentPage();
  224. mutateEditingMarkdown(pageData?.revision.body);
  225. };
  226. // If skipSSR is true, use the API to retrieve page data.
  227. // Because pageWIthMeta does not contain revision.body
  228. mutatePageData();
  229. }
  230. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  231. // sync grant data
  232. useEffect(() => {
  233. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  234. mutateSelectedGrant(grantDataToApply);
  235. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  236. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  237. useEffect(() => {
  238. const decodedURI = decodeURI(window.location.pathname);
  239. if (isClient() && decodedURI !== props.currentPathname) {
  240. const { search, hash } = window.location;
  241. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  242. }
  243. }, [props.currentPathname, router]);
  244. // initialize mutateEditingMarkdown only once per page
  245. // need to include useCurrentPathname not useCurrentPagePath
  246. useEffect(() => {
  247. if (props.currentPathname != null) {
  248. mutateEditingMarkdown(revisionBody);
  249. }
  250. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  251. useEffect(() => {
  252. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  253. mutateRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  254. }, [mutateRemoteRevisionId, mutateRevisionIdHackmdSynced, pageWithMeta?.data.revision?._id, pageWithMeta?.data.revisionHackmdSynced]);
  255. useEffect(() => {
  256. mutateCurrentPageId(pageId ?? null);
  257. }, [mutateCurrentPageId, pageId]);
  258. useEffect(() => {
  259. mutateIsNotFound(props.isNotFound);
  260. }, [mutateIsNotFound, props.isNotFound]);
  261. useEffect(() => {
  262. mutateIsLatestRevision(props.isLatestRevision);
  263. }, [mutateIsLatestRevision, props.isLatestRevision]);
  264. useEffect(() => {
  265. mutateTemplateTagData(props.templateTagData);
  266. }, [props.templateTagData, mutateTemplateTagData]);
  267. useEffect(() => {
  268. mutateTemplateBodyData(props.templateBodyData);
  269. }, [props.templateBodyData, mutateTemplateBodyData]);
  270. const title = generateCustomTitleForPage(props, pagePath);
  271. return (
  272. <>
  273. <Head>
  274. <title>{title}</title>
  275. </Head>
  276. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  277. <header className="py-0 position-relative">
  278. <div id="grw-subnav-container">
  279. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  280. </div>
  281. </header>
  282. <div className="d-edit-none">
  283. <GrowiSubNavigationSwitcher isLinkSharingDisabled={props.disableLinkSharing} />
  284. </div>
  285. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  286. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  287. <DisplaySwitcher
  288. pageView={
  289. <PageView
  290. pagePath={pagePath}
  291. initialPage={pageWithMeta?.data}
  292. rendererConfig={props.rendererConfig}
  293. />
  294. }
  295. />
  296. <PageStatusAlert />
  297. </div>
  298. </>
  299. );
  300. };
  301. type LayoutProps = Props & {
  302. children?: ReactNode
  303. }
  304. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  305. const className = useEditorModeClassName();
  306. // init sidebar config with UserUISettings and sidebarConfig
  307. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  308. return (
  309. <BasicLayout className={className}>
  310. {children}
  311. </BasicLayout>
  312. );
  313. };
  314. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  315. return (
  316. <>
  317. <GrowiPluginsActivator />
  318. <DrawioViewerScript />
  319. <Layout {...page.props}>
  320. {page}
  321. </Layout>
  322. <UnsavedAlertDialog />
  323. <DescendantsPageListModal />
  324. <DrawioModal />
  325. <HandsontableModal />
  326. <QuestionnaireModalManager />
  327. <TemplateModal />
  328. <LinkEditModal />
  329. </>
  330. );
  331. };
  332. function getPageIdFromPathname(currentPathname: string): string | null {
  333. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  334. }
  335. class MultiplePagesHitsError extends ExtensibleCustomError {
  336. pagePath: string;
  337. constructor(pagePath: string) {
  338. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  339. this.pagePath = pagePath;
  340. }
  341. }
  342. // apply parent page grant fot creating page
  343. async function applyGrantToPage(props: Props, ancestor: any) {
  344. await ancestor.populate('grantedGroup');
  345. const grant = {
  346. grant: ancestor.grant,
  347. };
  348. const grantedGroup = ancestor.grantedGroup ? {
  349. grantedGroup: {
  350. id: ancestor.grantedGroup.id,
  351. name: ancestor.grantedGroup.name,
  352. },
  353. } : {};
  354. props.grantData = Object.assign(grant, grantedGroup);
  355. }
  356. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  357. const { model: mongooseModel } = await import('mongoose');
  358. const req: CrowiRequest = context.req as CrowiRequest;
  359. const { crowi } = req;
  360. const { revisionId } = req.query;
  361. const Page = crowi.model('Page') as PageModel;
  362. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  363. const { pageService, configManager } = crowi;
  364. let currentPathname = props.currentPathname;
  365. const pageId = getPageIdFromPathname(currentPathname);
  366. const isPermalink = _isPermalink(currentPathname);
  367. const { user } = req;
  368. if (!isPermalink) {
  369. // check redirects
  370. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  371. if (chains != null) {
  372. // overwrite currentPathname
  373. currentPathname = chains.end.toPath;
  374. props.currentPathname = currentPathname;
  375. // set redirectFrom
  376. props.redirectFrom = chains.start.fromPath;
  377. }
  378. // check whether the specified page path hits to multiple pages
  379. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  380. if (count > 1) {
  381. throw new MultiplePagesHitsError(currentPathname);
  382. }
  383. }
  384. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  385. const page = pageWithMeta?.data as unknown as PageDocument;
  386. // add user to seen users
  387. if (page != null && user != null) {
  388. await page.seen(user);
  389. }
  390. // populate & check if the revision is latest
  391. if (page != null) {
  392. page.initLatestRevisionField(revisionId);
  393. props.isLatestRevision = page.isLatestRevision();
  394. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  395. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  396. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  397. }
  398. if (page == null && user != null) {
  399. const templateData = await Page.findTemplate(props.currentPathname);
  400. if (templateData != null) {
  401. props.templateTagData = templateData.templateTags as string[];
  402. props.templateBodyData = templateData.templateBody as string;
  403. }
  404. // apply pagrent page grant
  405. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  406. if (ancestor != null) {
  407. await applyGrantToPage(props, ancestor);
  408. }
  409. }
  410. props.pageWithMeta = pageWithMeta;
  411. }
  412. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  413. const req: CrowiRequest = context.req as CrowiRequest;
  414. const { crowi } = req;
  415. const Page = crowi.model('Page') as PageModel;
  416. const { currentPathname } = props;
  417. const pageId = getPageIdFromPathname(currentPathname);
  418. const isPermalink = _isPermalink(currentPathname);
  419. const page = props.pageWithMeta?.data;
  420. if (props.isIdenticalPathPage) {
  421. props.isNotCreatable = true;
  422. }
  423. else if (page == null) {
  424. props.isNotFound = true;
  425. props.isNotCreatable = !isCreatablePage(currentPathname);
  426. // check the page is forbidden or just does not exist.
  427. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  428. props.isForbidden = count > 0;
  429. }
  430. else {
  431. props.isNotFound = page.isEmpty;
  432. props.isNotCreatable = false;
  433. props.isForbidden = false;
  434. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  435. if (isPermalink && page.isEmpty) {
  436. props.currentPathname = page.path;
  437. }
  438. // /path/to/page ==> /62a88db47fed8b2d94f30000
  439. if (!isPermalink && !page.isEmpty) {
  440. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  441. if (!isToppage) {
  442. props.currentPathname = `/${page._id}`;
  443. }
  444. }
  445. }
  446. }
  447. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  448. // const req: CrowiRequest = context.req as CrowiRequest;
  449. // const { crowi } = req;
  450. // const UserModel = crowi.model('User');
  451. // if (isUserPage(props.currentPagePath)) {
  452. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  453. // if (user != null) {
  454. // props.pageUser = JSON.stringify(user.toObject());
  455. // }
  456. // }
  457. // }
  458. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  459. const req: CrowiRequest = context.req as CrowiRequest;
  460. const { crowi } = req;
  461. const {
  462. searchService, configManager, aclService,
  463. } = crowi;
  464. props.isSearchServiceConfigured = searchService.isConfigured;
  465. props.isSearchServiceReachable = searchService.isReachable;
  466. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  467. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  468. // props.isMailerSetup = mailService.isMailerSetup;
  469. props.isAclEnabled = aclService.isAclEnabled();
  470. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  471. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  472. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  473. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  474. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  475. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  476. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  477. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  478. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  479. props.editorConfig = {
  480. upload: {
  481. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  482. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  483. },
  484. };
  485. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  486. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  487. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  488. props.rendererConfig = {
  489. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  490. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  491. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  492. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  493. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  494. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  495. // XSS Options
  496. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  497. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  498. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  499. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  500. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  501. };
  502. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  503. }
  504. /**
  505. * for Server Side Translations
  506. * @param context
  507. * @param props
  508. * @param namespacesRequired
  509. */
  510. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  511. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  512. props._nextI18Next = nextI18NextConfig._nextI18Next;
  513. }
  514. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  515. const req = context.req as CrowiRequest<IUserHasId & any>;
  516. const { user } = req;
  517. const result = await getServerSideCommonProps(context);
  518. // check for presence
  519. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  520. if (!('props' in result)) {
  521. throw new Error('invalid getSSP result');
  522. }
  523. const props: Props = result.props as Props;
  524. if (props.redirectDestination != null) {
  525. return {
  526. redirect: {
  527. permanent: false,
  528. destination: props.redirectDestination,
  529. },
  530. };
  531. }
  532. if (user != null) {
  533. props.currentUser = user.toObject();
  534. }
  535. try {
  536. await injectPageData(context, props);
  537. }
  538. catch (err) {
  539. if (err instanceof MultiplePagesHitsError) {
  540. props.isIdenticalPathPage = true;
  541. }
  542. else {
  543. throw err;
  544. }
  545. }
  546. await injectRoutingInformation(context, props);
  547. injectServerConfigurations(context, props);
  548. await injectNextI18NextConfigurations(context, props, ['translation']);
  549. return {
  550. props,
  551. };
  552. };
  553. export default Page;